<?php
abstract class resource_api_abstract implements resource_api_interface {
	
	protected static $_isInDtabase = false;
	protected static function saveToDatabase($data, $type = 'image') {
		try {
			$_type = new resource_file_type($type);
			$content = new resource_file_concept();
			if(!($row = $content->fetch(array('hash = ?' => $data['hash'], 'type = ?' => $_type->getId())))) {
				$row = $content->create();
				$row->setHash($data['hash']);
				$row->setType($_type->getId());
				$row->setSize($data['size']);
				$row->setExtension($data['ext']);
				$row->setWidth($data['dimension']['width']);
				$row->setHeight($data['dimension']['height']);
			} else {
				self::$_isInDtabase = true;
			}
			return $row;
		} catch (Exception $e) {
			throw new resource_exception($e->getMessage());
		}
	}
	
	protected static function saveRemoteToLocal($http) {
		$adapter = curl_init();
		curl_setopt($adapter, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($adapter, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($adapter, CURLOPT_URL, $http);
		curl_setopt($adapter, CURLOPT_POST, false);
		curl_setopt($adapter, CURLOPT_HEADER, false);
		$content = curl_exec($adapter);		
		curl_close($adapter);
		
		$filename = _DIRECTORY_VAR . DIRECTORY_SEPARATOR . 
					'tmp' . DIRECTORY_SEPARATOR . 'remote' . DIRECTORY_SEPARATOR . md5(time() . rand(1000, 9999)) . '.tmp';
		
		system_file_io::mkdir(dirname($filename));
		if(!file_put_contents($filename, $content)) {
			throw new resource_exception("Save file faild,Please check if the folder is writable.");
		}
			
		return array (
            'tmp_name' => $filename,
            'size' => filesize($filename)
        );
	}
		
}
